# -*- coding: utf-8 -*-
from  xml.dom.minidom import parseString, parse
import re

class ROW(object):
    """
        clase implementada en tiempo de ejecucion
        representa un objeto-nodoXml
    """
    pass

class Xml_to_objects(object):
    """
        Realiza el mapeo XML-objeto para cada tag Xml
    """

    lista = []

    def __init__(self, path, clase):
        self.clase = clase
        xml = self._read_file(path)
        self.dom = parseString(xml)
        self.class_name = self._get_class_element()
        self.node_list = self.dom.getElementsByTagName(self.class_name)
        self._get_tag_and_text()

    def _get_class_element(self):
        first = self.dom.firstChild
        for child in first.childNodes:
            if child.nodeType == child.ELEMENT_NODE:
                return child.tagName

    def _read_file(self, path):
        f = open(path, "r")
        content = f.read()
        return content

    def _get_text(self, node):
        return node.data.encode('utf-8')

    def _get_tag_and_text(self):
        for node in self.node_list:
            obj = self.clase()
            for n in node.childNodes:
                if n.nodeType == n.ELEMENT_NODE:
                    value = self._get_text(n.childNodes[0])
                    setattr(self.clase, n.tagName, value)
            self.lista.append(obj)

    def get_objects(self):
        return self.lista

    def get_attributes(self, obj):
        atributos = []
        for k,v in obj.__class__.__dict__.iteritems():
            if re.match("[A-Za-z]+", str(k)):
                atributos.append((str(k),str(v)))
        return atributos

if __name__ == "__main__":

    parser = Xml_to_objects(xml , ROW)
    objects = parser.get_objects()

    for row in objects:
        print ""
        for k,v in row.__class__.__dict__.iteritems():
            if re.match("[A-Za-z]+", str(k)):
                print "key: " + str(k) + " - value: " + str(v)



